package com.qf.springcloud.aircore.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.qf.springcloud.aircore.client.SearchClient;
import jdk.nashorn.internal.runtime.JSONFunctions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@RestController
public class CoreController {

//    @Autowired
//    private RestTemplate restTemplate;

//    @Resource
//    private EurekaClient eurekaClient;

    @Resource
    private SearchClient searchClient;

    @Value("${spring.application.name}")
    private String name;

    @HystrixCommand(fallbackMethod = "testFallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.strategy",value = "THREAD"),
            @HystrixProperty(name = "circuitBreaker.enabled",value = "false")
    })
    @GetMapping("/core/test")
    public String test(String id) throws InterruptedException {
        /*// 通过Eureka获取SEARCH服务的ip和端口
        InstanceInfo searchInfo = eurekaClient.getNextServerFromEureka("search", false);
        String ip = searchInfo.getIPAddr();
        int port = searchInfo.getPort();
        // 调用search服务中的接口，/search/test
        String result = restTemplate.getForObject("http://"+ip+":"+port+"/search/test", String.class);
        // 调用search模块,使用restTemplate发起请求
//        String result = restTemplate.getForObject("http://search/search/test", String.class);
        // 轮询
*/
        if("1".equals(id)){
            int i = 1 / 0;
        }
        System.out.println(Thread.currentThread().getName());
        String result = searchClient.searchTest();
        return result + name;
    }

    public String testFallback(String id){
        return "啊，我凉了！";
    }














    @PostMapping("/core/add")
    public Map add(@RequestBody Map map){
        Map result = searchClient.add(map);
        return result;
    }

    @DeleteMapping("/core/del/{id}")
    public String del(@PathVariable String id){
        System.out.println(Thread.currentThread().getName());
        String result = searchClient.del(id);
        return result;
    }

    @PostMapping("/core/update")
    public String update(String name, Integer age, @DateTimeFormat(pattern = "yyyy-MM-dd") Date birthday){
        String result = searchClient.update(name, age, birthday);
        return result;
    }



}
